import dayjs from 'dayjs';
/**
 * 多语言配置文件
 */
import I18n from 'i18n-js';
import * as RNLocalize from 'react-native-localize';
import lanKeys from './keyMap';
import zh from './zh';
import en from './en';
import {ReduxStore} from 'reduxState/store';

type ParamType = {
  [key: string]: string | ParamType;
};
type lanKeysType = typeof lanKeys;

export type LanType<T> = {
  (key: keyof T): string;
  (key: string): string;
};
export type LanSetting = 'en' | 'zh';
const locales = RNLocalize.getLocales();
const systemLanguage = locales[0]?.languageCode; // 用户系统偏好语言

const {
  settingsState: {locale},
} = ReduxStore.getState(); // 用户手动设置语言

if (locale) {
  I18n.locale = locale;
} else if (systemLanguage) {
  I18n.locale = systemLanguage;
} else {
  I18n.locale = 'en'; // 默认语言为英文
}

// 监听应用运行过程中语言的变化
ReduxStore.subscribe(() => {
  const {
    settingsState: {locale: newLocale},
  } = ReduxStore.getState(); // 用户手动设置语言
  if (newLocale && newLocale !== I18n.locale) {
    I18n.locale = newLocale;
    dayjs.locale(newLocale);
  }
});
I18n.fallbacks = true;
I18n.translations = {
  zh,
  en,
};

export default I18n.t.bind(I18n) as LanType<lanKeysType>;

export {systemLanguage};
